import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import { Alert, message, Tooltip, Skeleton, Tag } from 'antd';
import { useRequest, defaultFormatResult, useWorkFlow } from '@/hooks';

import {
    queryEmployeeArchiveHead,
    queryImmediateSuperior,
    queryChargeNumber
} from '@/pages/Organization/EmployeeManage/services';
import UploadAvatar from '@/containers/UploadAvatar';
import { history } from 'umi';
import moment from 'moment';
import IconFont from '@/components/IconFont';
import ControlsItemRestPassword from '@/pages/Organization/EmployeeManage/components/EmployeeCard/components/ControlsItemRestPassword';
import ControlsItemVVCard from '@/pages/Organization/EmployeeManage/components/EmployeeCard/components/ControlsItemVVCard';
import ControlsItemInviteImproveInfo from '@/pages/Organization/EmployeeManage/components/EmployeeCard/components/ControlsItemInviteImproveInfo';
import { updateemployeeavatar, uploademployeeavatar } from '@/services/user';
import authHelper from '@/utils/auth/helper';
import AuthComponent from '@/utils/auth/AuthComponent';
import { createDictionary } from '@/dictionary';
import { eventTrack } from '@/utils/track';
import { newTabProps } from '@/utils/tab';
import { connect } from 'umi';
import styles from './index.less';

const workNatureUnitMap = {
    full_time: '全职',
    part_time: '兼职',
    practice: '实习',
    consultant: '顾问',
    temporary: '临时工'
};
const [, getServiceStatusName] = createDictionary('SERVICE_STATUS_DICT');
const hasSuperiorAuth = authHelper.checkCode('office:orgs:employee:detail');

/**
 * 员工的基本信息面板
 * @param employeeCode 员工id
 * @param dutyCode 岗位code, 为空为主岗
 * @param isPersonalPage 是否是个人档案页面
 * @param currentTabKey 当前的选项卡, 保证每次查看上级能看到同一选项卡的内容
 * @param hasEmployeePermission 是否有查看当前员工的权限
 * @param props 其他属性
 * @returns {*}
 * @constructor
 */

const EmployeeCard = ({
    employeeCode,
    dutyCode,
    isPersonalPage,
    currentTabKey,
    hasEmployeePermission,
    dispatch,
    ...props
}) => {
    // 用户数据
    const {
        data: employeeInfoData,
        error: employeeInfoError,
        loading: employeeInfoLoading,
        refresh: employeeInfoRefresh
    } = useRequest(() => queryEmployeeArchiveHead({ employeeCode, dutyCode }), {
        cacheKey: `employee-info-${employeeCode}-${dutyCode}`,
        refreshDeps: [employeeCode, dutyCode],
        ...defaultFormatResult
    });
    // 直接上级数据
    const { data: immediateSuperiorData, loading: immediateSuperiorLoading } = useRequest(
        () => queryImmediateSuperior({ employeeCode, dutyCode }),
        {
            cacheKey: `employee-immediateSuperior-${employeeCode}-${dutyCode}`,
            refreshDeps: [employeeCode, dutyCode],
            ...defaultFormatResult
        }
    );
    // 直属下级数据
    const { data: chargeNumberData, loading: chargeNumberLoading } = useRequest(
        () => queryChargeNumber({ employeeCode, dutyCode }),
        {
            cacheKey: `employee-chargeNumber-${employeeCode}-${dutyCode}`,
            refreshDeps: [employeeCode, dutyCode],
            ...defaultFormatResult
        }
    );
    // 更新头像
    const { run: updateAvatar } = useRequest(updateemployeeavatar, {
        manual: true
    });
    const { run: uploadAvatar } = useRequest(uploademployeeavatar, {
        manual: true
    });

    // 更新头像
    const handleUpdateAvatar = ({ uploadResourceFile, preUrl, file }) => {
        const action = employeeInfoData.avatarFile?.length ? updateAvatar : uploadAvatar;
        // 上传进度
        const progressOptions = { file };
        fetch(
            preUrl,
            {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/octet-stream'
                },
                body: file
            },
            progressOptions
        ).then(() => {
            action({
                areaCode: '',
                employeeCode: employeeInfoData.employeeCode,
                mobile: '',
                resourceRelation: [uploadResourceFile]
            }).then(res => {
                console.log();
                if (res.code === 10000) {
                    if (employeeInfoData.avatarFile?.length) {
                        message.success('修改成功');
                    } else {
                        message.success('上传成功');
                    }
                    employeeInfoRefresh().then(e => {
                        dispatch({
                            type: 'user/fixAvatarFile',
                            payload: {
                                avatarFile: e.avatarFile
                            }
                        });
                    });
                } else {
                    message.error(res.msg);
                }
            });
        });
    };

    const { launch } = useWorkFlow({ launchParam: { type: 'DimissionProxyApply' } });
    // 离职, 发起离职审批
    const handleLeaveOffice = () => {
        launch({ leaverEmployeeCode: employeeCode });
    };

    // 直接上级
    const renderImmediateSuperior = data => {
        const handleImmediateSuperiorClick = item => {
            const query = {
                employeeCode: item.employeeCode,
                dutyCode: item.dutyCode,
                tab: currentTabKey
            };
            if (currentTabKey) {
                query.tab = currentTabKey;
            }
            history.push({
                pathname: '/office/personnelManagement/organization/employeeList/detail',
                query,
                ...newTabProps
            });
        };
        if (!data || data.length === 0) {
            return '--';
        }
        return data.map(item =>
            hasSuperiorAuth ? ( // 有查看员工详情的权限才可以查看
                <a
                    key={item.employeeCode}
                    onClick={() => handleImmediateSuperiorClick(item)}
                    style={{ marginRight: '6px' }}
                >
                    {item.employeeName}
                </a>
            ) : (
                <span key={item.employeeCode} style={{ marginRight: '6px' }}>
                    {item.employeeName}
                </span>
            )
        );
    };

    // 陪伴天数
    const renderDaysOfEntry = useMemo(() => {
        if (employeeInfoData?.timeOfEntry && employeeInfoData.serviceStatus !== 6) {
            if (new Date().getTime() < new Date(employeeInfoData.timeOfEntry).getTime()) {
                return <div className={styles.employeeDays}>微微期待你的加入!</div>;
            }
            const diffDay = moment(new Date()).diff(moment(employeeInfoData.timeOfEntry), 'day') + 1;
            return (
                <div className={styles.employeeDays}>
                    今天是你陪伴微微成长的第 <strong>{diffDay}</strong> 天
                </div>
            );
        }
        return null;
    }, [employeeInfoData]);

    // 数据获取错误处理
    if (employeeInfoError || (!employeeInfoLoading && !employeeInfoData)) {
        return (
            <Alert
                style={{ marginBottom: '20px' }}
                type="error"
                message={employeeInfoError?.msg || '员工数据加载失败'}
            />
        );
    }

    return (
        <div className={styles.employeeCard} {...props}>
            {/* 使用 employeeInfoData 做loading 条件, 是想使用缓存, 有缓存信息就直接显示 */}
            <Skeleton loading={employeeInfoLoading || immediateSuperiorLoading || chargeNumberLoading} active avatar>
                {employeeInfoData && (
                    <>
                        <div style={{ marginRight: '20px' }}>
                            <UploadAvatar
                                value={{ allFileList: employeeInfoData.avatarFile }}
                                editable={
                                    employeeInfoData.serviceStatus !== 6 && (
                                        isPersonalPage ||
                                        (hasEmployeePermission && authHelper.checkCode('office:orgs:employee:detail:updateAvatar'))
                                    )
                                }
                                onChange={handleUpdateAvatar}
                            />
                        </div>
                        <div className={styles.employeeContent}>
                            <div>
                                <h3 className={styles.employeeName}>{employeeInfoData.employeeName}</h3>
                                {employeeInfoData.userName && <small>/ {employeeInfoData.userName}</small>}
                            </div>
                            <div className={styles.employeeMeta}>
                                <div className={styles.employeeMetaItem}>{employeeInfoData.fullDepartmentName}</div> -
                                <div className={styles.employeeMetaItem}>{employeeInfoData.dutyAlias}</div>
                            </div>
                            <div className={styles.employeeMeta}>
                                <Tag>
                                    {employeeInfoData.positionName}/{employeeInfoData.rankValue}
                                </Tag>
                                <Tag>{getServiceStatusName(employeeInfoData.serviceStatus)}</Tag>
                                {employeeInfoData.workNature && (
                                    <Tag>{workNatureUnitMap[employeeInfoData.workNature]}</Tag>
                                )}
                            </div>
                            <div className={styles.employeeMeta} style={{ marginTop: '10px' }}>
                                <span>直接上级： {renderImmediateSuperior(immediateSuperiorData)}</span>
                                &emsp;&emsp;
                                <span>分管下属：{chargeNumberData || 0}</span>
                                <span style={{ marginLeft: '15px' }}>
                                    行政机构： {employeeInfoData.administrativeOrganizationName}
                                </span>
                            </div>
                        </div>
                        <div className={styles.employeeControls}>
                            {isPersonalPage && (
                                <>
                                    {/* {employeeInfoData.serviceStatus === 4 && (
                                        <AuthComponent code="office:orgs:employee:turn">
                                            <Tooltip title="申请转正">
                                                <div
                                                    className={`${styles.employeeControlsItemDisabled} ${styles.employeeControlsItem}`}
                                                    // onClick={() => history.push({ pathname: '' })}
                                                >
                                                    <IconFont icon="iconlistfunction_jobtransfer_icon_default" />
                                                </div>
                                            </Tooltip>
                                        </AuthComponent>
                                    )}
                                    {[1, 4, 5, 9].includes(employeeInfoData.serviceStatus) && (
                                        <AuthComponent code="office:orgs:employee:transfer">
                                            <Tooltip title="申请调岗">
                                                <div
                                                    className={`${styles.employeeControlsItemDisabled} ${styles.employeeControlsItem}`}
                                                    // onClick={() => history.push({ pathname: '' })}
                                                >
                                                    <IconFont icon="iconlistfunction_jobswitch_icon_default" />
                                                </div>
                                            </Tooltip>
                                        </AuthComponent>
                                    )} */}
                                    <Tooltip title="修改密码">
                                        <div
                                            className={styles.employeeControlsItem}
                                            onClick={async () => {
                                                // 埋点
                                                await eventTrack({
                                                    eventName: 'personal_my_info_setpassword_click',
                                                    pageName: 'personal_my_info'
                                                });
                                                history.push({
                                                    pathname: '/personalCenter/passwordSettings'
                                                    // state: { tabRoute: true, tabRefresh: true }
                                                });
                                            }}
                                        >
                                            <IconFont icon="iconpassword" />
                                        </div>
                                    </Tooltip>
                                </>
                            )}
                            {[1, 4, 9].includes(employeeInfoData.serviceStatus) && hasEmployeePermission && (
                                <AuthComponent code="office:orgs:employee:regisn">
                                    <Tooltip title="发起离职申请">
                                        <div className={styles.employeeControlsItem} onClick={handleLeaveOffice}>
                                            <IconFont icon="iconlistfunction_absence_icon_default" />
                                        </div>
                                    </Tooltip>
                                </AuthComponent>
                            )}
                            {!isPersonalPage && hasEmployeePermission && employeeInfoData.serviceStatus !== 6 && (
                                // 员工档案的类型下, 如果是当前用户不显示这些操作
                                <>
                                    {/* 重置密码 */}
                                    <AuthComponent code="office:orgs:employee:detail:password">
                                        <ControlsItemRestPassword employeeInfo={employeeInfoData} />
                                    </AuthComponent>
                                    {/* 邀请完善信息 */}
                                    <AuthComponent code="office:orgs:employee:detail:invitefil">
                                        <ControlsItemInviteImproveInfo employeeInfo={employeeInfoData} />
                                    </AuthComponent>
                                </>
                            )}
                            {/* 名片 */}
                            {employeeInfoData.serviceStatus !== 6 &&
                                <ControlsItemVVCard employeeInfo={employeeInfoData} />}
                        </div>
                        {renderDaysOfEntry}
                    </>
                )}
            </Skeleton>
        </div>
    );
};

// prop
EmployeeCard.propTypes = {
    employeeCode: PropTypes.string.isRequired,
    dutyCode: PropTypes.string,
    isPersonalPage: PropTypes.bool,
    currentTabKey: PropTypes.string
};

EmployeeCard.defaultProps = {
    dutyCode: null,
    isPersonalPage: false,
    currentTabKey: ''
};
export default connect(() => ({}))(EmployeeCard);
